package net.hky365.lowcode.magic.interceptor;

import lombok.RequiredArgsConstructor;
import net.hky365.shop.framework.common.enums.UserTypeEnum;
import net.hky365.shop.framework.common.util.CommonUtils;
import net.hky365.shop.framework.common.util.servlet.ServletUtils;
import net.hky365.shop.framework.security.config.SecurityProperties;
import net.hky365.shop.framework.security.core.api.oauth2.OAuth2TokenApi;
import net.hky365.shop.framework.security.core.api.oauth2.UserApi;
import net.hky365.shop.framework.security.core.api.oauth2.dto.OAuth2AccessTokenCheckRespDTO;
import net.hky365.shop.framework.security.core.service.SecurityFrameworkService;
import net.hky365.shop.framework.security.core.util.SecurityFrameworkUtils;
import net.hky365.shop.framework.tenant.core.aop.TenantIgnore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.MagicUser;
import org.ssssssss.magicapi.core.exception.MagicLoginException;
import org.ssssssss.magicapi.core.interceptor.AuthorizationInterceptor;

import java.util.Optional;

/**
 * magic api 用户登录验证
 *
 * @author hl-king
 */
@Component
@RequiredArgsConstructor
public class MagicAuthorizationInterceptor implements AuthorizationInterceptor {
    private static final Logger log = LoggerFactory.getLogger(MagicAuthorizationInterceptor.class);
    private final SecurityProperties securityProperties;
    private final SecurityFrameworkService securityFrameworkService;
    private final OAuth2TokenApi oauth2TokenApi;
    private final UserApi userApi;

    /**
     * 配置是否需要登录
     */
    @Override
    public boolean requireLogin() {
        return true;
    }

    /**
     * 根据Token获取User
     */
    @Override
    @TenantIgnore
    // @PreAuthorize("@ss.hasPermission('lowcode:margic:manage')")
    public MagicUser getUserByToken(String token) throws MagicLoginException {
        UserApi.UserInfo user = SecurityFrameworkUtils.getLoginUser();
        if (user == null) {
            // on Login 事件, 此处无法获取request 没有上下文
            OAuth2AccessTokenCheckRespDTO authUser = oauth2TokenApi.checkAccessToken(token);
            if (authUser != null) {
                user = userApi.getUserById(authUser.getUserId(), UserTypeEnum.ADMIN);
            }
        }

        if (user == null || !securityFrameworkService.hasAnyPermissions(user.getId(), "lowcode:magic:manage")) {
            log.error("unAuthed user try access magic api, {}", user);
            throw new MagicLoginException("UnKnow user");
        }
        // 创建session
        Optional.ofNullable(ServletUtils.getRequest()).ifPresent(it -> ServletUtils.getRequest().getSession(true));
        return new MagicUser(CommonUtils.toString(user.getId()), user.getNickname(), token);
    }

    @Override
    public MagicUser login(String username, String password) throws MagicLoginException {
        //     // 登录成功后 构造MagicUser对象。
        //     return new MagicUser("1", "admin", "token value......")
        throw new MagicLoginException("用户名或密码不正确");
    }
}